﻿package com.ruiyi.adrobot.component;

import com.alibaba.fastjson.JSONObject;
import com.ruiyi.adrobot.beans.*;
import com.ruiyi.adrobot.beans.dto.TaskExcuteBaseInfo;
import com.ruiyi.adrobot.beans.socket.SocketRequest;
import com.ruiyi.adrobot.mongo.device.DeviceRepository;
import com.ruiyi.adrobot.mongo.robot.RobotRepository;
import com.ruiyi.adrobot.mongo.taskdetail.TaskDetailRepository;
import com.ruiyi.adrobot.service.accountinfo.AccountInfoService;
import com.ruiyi.adrobot.service.device.DeviceService;
import com.ruiyi.adrobot.service.vpn.VpnService;
import com.ruiyi.adrobot.utils.DateUtil;
import com.ruiyi.adrobot.utils.LoggerUtil;
import com.ruiyi.adrobot.web.socket.ChannelInitializerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.commons.collections4.map.LinkedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * Created by 51102 on 2017/6/24.
 */
@Component
public class TaskExcuter {
    @Autowired
    private TaskDetailRepository taskDetailRepository;
    @Autowired
    private RobotRepository robotRepository;
    @Autowired
    private DeviceRepository deviceRepository;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private VpnService vpnService;
    @Autowired
    private AccountInfoService accountInfoService;
    @Resource(name = "redisTemplate")
    private ValueOperations<String, Integer> redisOperations;
    public static Map<String, Queue> queueMap = new ConcurrentHashMap();
    public static List<String> stopTaskList = Collections.synchronizedList(new ArrayList<String>());

    /**
     * 初始化netty
     */
    @Async
    public void initNetty() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childHandler(new ChannelInitializerHandler());
            //设置参数，TCP参数
            bootstrap.option(ChannelOption.SO_BACKLOG, 2048);//serverSocketchannel的设置，链接缓冲池的大小
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);//socketchannel的设置,维持链接的活跃，清除死链接
            bootstrap.childOption(ChannelOption.TCP_NODELAY, true);//socketchannel的设置,关闭延迟发送
            bootstrap.bind(2406).sync().channel().closeFuture().sync();
            LoggerUtil.debug("*************************Netty已启动************************");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    @Async
    public void offerTask2Queue(TaskDetail taskDetail) {
        List<TaskDetail.Task> tasks = taskDetailRepository.findTasksByTaskDetailIdAndNotSent(taskDetail.getId());
        for (TaskDetail.Task task : tasks) {
            try {
                if (stopTaskList.contains(taskDetail.getId())) {
                    stopTaskList.remove(taskDetail.getId());
                    return;
                }
                while (DateUtil.getTimeByString(task.getStartTime()) > new Date().getTime()) {
                    LoggerUtil.info("未到任务执行时间暂停60秒" + taskDetail.getId());
                    SECONDS.sleep(60);
                }
                // 将任务放入queue
                String startDate = null;
                String endDate = null;
                Fun.Flow.Action action = null;
                for (TaskConfig.Flow flow : taskDetail.getFlows()) {
                    if (flow.getId().equals(task.getFlowId())) {
                        startDate = flow.getStartDate();
                        endDate = flow.getEndDate();
                        action = flow.getAction();
                        break;
                    }
                }
                QueueTask queueTask = new QueueTask(taskDetail.getId(), taskDetail.getFun(), taskDetail.getGroupNames(), task, startDate, endDate, action, taskDetail.getDidType(), taskDetail.getDeviceType());
                if (null == queueMap.get(taskDetail.getId())) {
                    Queue queue = new ConcurrentLinkedQueue();
                    queue.offer(queueTask);
                    queueMap.put(taskDetail.getId(), queue);
                } else {
                    queueMap.get(taskDetail.getId()).offer(queueTask);
                }
                LoggerUtil.info(taskDetail.getId() + "队列池中任务数量" + queueMap.get(taskDetail.getId()).size());
            } catch (Exception e) {
                LoggerUtil.error("任务分配线程发生异常:" + taskDetail.getId());
                LoggerUtil.info(taskDetail.getId() + "队列池中任务数量" + queueMap.get(taskDetail.getId()).size());
                e.printStackTrace();
                continue;
            }
        }
        LoggerUtil.info("发现任务且已分配完成暂停30秒" + taskDetail.getId());
        try {
            SECONDS.sleep(30);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Async
    public void excuteQueueTask() {
        while (true) {
            try {
                if (queueMap.size() > 0) {
                    for (Map.Entry<String, Queue> entry : queueMap.entrySet()) {
                        QueueTask queueTask = (QueueTask) entry.getValue().poll();
                        if (null == queueTask) {
                            queueMap.remove(entry.getKey());
                            break;
                        }

                        if (!excuteTask(queueTask)) {
                            queueMap.get(queueTask.getTaskDetailId()).offer(queueTask);
                        }
                        LoggerUtil.info(queueTask.getTaskDetailId() + "队列中任务数量:" + queueMap.get(queueTask.getTaskDetailId()).size());
                    }
                } else {
                    LoggerUtil.info("线程队列中没有任务暂停10秒");
                    SECONDS.sleep(10);
                }
            } catch (Exception e) {
                LoggerUtil.info("任务停止后发生读取异常，任然可正常运行");
            }
        }
    }


    private Boolean excuteTask(QueueTask queueTask) throws InterruptedException {
        // 开始分配任务
        long startTime = System.currentTimeMillis();
        TaskExcuteBaseInfo taskExcuteBaseInfo = buildTaskExcuteBaseInfo(queueTask);
        if (taskExcuteBaseInfo.getErrorCode() != 0) {
            TimeUnit.SECONDS.sleep(1);
            return false;
        }
        String excuteSimCode = taskExcuteBaseInfo.getExcuteSimCode();
        Device excuteDevice = taskExcuteBaseInfo.getExcuteDevice();
        TaskExcuteBaseInfo.VpnInfo vpnInfo = taskExcuteBaseInfo.getVpnInfo();
        // 任务执行的模拟设备信息
        queueTask.getTask().setDevice(excuteDevice);
        // 发送任务
        buildRobotVpnIp(excuteSimCode, vpnInfo.getIp());
        int i = 0;
        Boolean busy;
        do {
            NettyChannelhandlerContextMap.get(excuteSimCode).writeAndFlush(buildSocketRequest(queueTask.getTaskDetailId(), queueTask.getTask(), vpnInfo, queueTask.getAction()).toString());
            // 检查设备是否忙碌判定任务是否发送成功
            TimeUnit.SECONDS.sleep(5);
            busy = robotRepository.findBySimCode(excuteSimCode).getBusy();
            if (busy) {
                break;
            } else if (i++ == 1) {
                return false;
            }
        } while (busy == false);
        // 记录任务相关信息
        updateTaskInfo(queueTask.getTaskDetailId(), queueTask.getTask(), excuteSimCode, excuteDevice, vpnInfo, taskExcuteBaseInfo.getTaskDynamicInfos(), queueTask.getFun());
        LoggerUtil.info("任务已发送用时:" + (System.currentTimeMillis() - startTime));
        return true;
    }

    private void buildRobotVpnIp(String excuteSimCode, String vpnIp) {
        // 释放设备ip
        String usedVpnIp = robotRepository.findBySimCode(excuteSimCode).getVpnIp();
        if (StringUtils.hasText(usedVpnIp)) {
            vpnService.releaseIp(usedVpnIp);
            LoggerUtil.info("IP已释放：" + usedVpnIp);
        }
        // 保存设备ip
        Update updateRobot = new Update();
        updateRobot.set("vpnIp", vpnIp);
        robotRepository.updateBySimCode(excuteSimCode, updateRobot);
    }

    private TaskExcuteBaseInfo buildTaskExcuteBaseInfo(QueueTask queueTask) {
        TaskExcuteBaseInfo taskExcuteBaseInfo = new TaskExcuteBaseInfo();
        try {
            boolean virtual = queueTask.getDeviceType() == 1 ? true : false;
            // 筛选出組中能执行任务、处于空闲、在线的Robot
            List<Robot> canExcuteRobots = robotRepository.getCanExcuteRobotsByOnlineAndBusyAndGroupNameAndLockTimeLessThan(queueTask.getGroupNames());
            List<String> usedImeis = taskDetailRepository.findUsedImeisById(queueTask.getTaskDetailId());
            if (canExcuteRobots.size() == 0) {
                LoggerUtil.info("沒有可用的Robot:暂停1秒");
                return TaskExcuteBaseInfo.errorCode(1);
            }
            if (queueTask.getTask().getStepType3() != -1) {
                // 根据空闲设备的设备型号循环查找匹配的账号
                AccountInfo.Account account = accountInfoService.findRandomAccount(queueTask.getFun(), virtual, queueTask.getStartDate(), queueTask.getEndDate(), usedImeis, canExcuteRobots);
                if (null == account) {
                    LoggerUtil.info("老用户不足");
                    return TaskExcuteBaseInfo.errorCode(2);
                }
                taskExcuteBaseInfo.setExcuteSimCode(account.getExcuteSimCode());
                taskExcuteBaseInfo.setExcuteDevice(deviceService.findDeviceByImei(account.getImei(), virtual));
                // 输入用户名和密码赋值
                taskExcuteBaseInfo.setTaskDynamicInfos(fillAccount(queueTask, account));
            } else {
                Device excuteDevice = deviceService.findRandomNotUsedDevice(queueTask.getFun(), virtual, canExcuteRobots);
                if (null == excuteDevice) {
                    LoggerUtil.info("设备型号不足");
                    return TaskExcuteBaseInfo.errorCode(3);
                }
                taskExcuteBaseInfo.setExcuteSimCode(excuteDevice.getExcuteSimCode());
                taskExcuteBaseInfo.setExcuteDevice(excuteDevice);
            }
            // 获取vpnHost
            JSONObject jsonObject = getVpn(taskExcuteBaseInfo.getExcuteDevice().getProvinceId(), taskExcuteBaseInfo.getExcuteDevice().getCityId(), queueTask.getDidType(), taskExcuteBaseInfo.getExcuteDevice());
            if (null == jsonObject) {
                LoggerUtil.info("获取vpn失败");
                if (queueTask.getDidType() == 2) {
                    // 若精确ip到城市，很多情况获取不到对应的ip，则跳过该设备的账号
                    updateUsedImei(queueTask.getTaskDetailId(), taskExcuteBaseInfo.getExcuteDevice().getImei());
                }
                return TaskExcuteBaseInfo.errorCode(4);
            }
            TaskExcuteBaseInfo.VpnInfo vpnInfo = new TaskExcuteBaseInfo.VpnInfo(jsonObject.getString("ip"), jsonObject.getString("username"), jsonObject.getString("password"), jsonObject.getInteger("online"));
            taskExcuteBaseInfo.setVpnInfo(vpnInfo);
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtil.info("获取任务基本信息时，未知异常");
            return TaskExcuteBaseInfo.errorCode(5);
        }
        return taskExcuteBaseInfo;
    }

    private List<TaskDetail.Task.TaskDynamicInfo> fillAccount(QueueTask queueTask, AccountInfo.Account account) {
        List<TaskDetail.Task.TaskDynamicInfo> taskDynamicInfos = new LinkedList<>();
        queueTask.getAction().getSteps().get(queueTask.getTask().getStepType3()).setViewText(account.getUserName());
        taskDynamicInfos.add(new TaskDetail.Task.TaskDynamicInfo(queueTask.getTask().getStepType3(), account.getUserName()));
        Integer stepType;
        int l = 1;
        do {
            stepType = queueTask.getAction().getSteps().get(queueTask.getTask().getStepType3() + l).getStepType();
            l++;
        } while (stepType != 4);
        queueTask.getAction().getSteps().get(queueTask.getTask().getStepType3() + l - 1).setViewText(account.getPwd());
        taskDynamicInfos.add(new TaskDetail.Task.TaskDynamicInfo(queueTask.getTask().getStepType3() + l - 1, account.getPwd()));
        return taskDynamicInfos;
    }


    private void updateTaskInfo(String taskDetailId, TaskDetail.Task task, String excuteSimCode, Device excuteDevice, TaskExcuteBaseInfo.VpnInfo vpnInfo, List<TaskDetail.Task.TaskDynamicInfo> taskDynamicInfos, Integer fun) {
        // 记录二次登陆使用的imei
        updateUsedImei(taskDetailId, excuteDevice.getImei());
        // 标记该设备已使用
        signUsedDevice(excuteDevice, fun);
        // 锁定Robot60秒
        lockRobot(excuteSimCode);
        // 记录IP剩余连接数
        redisOperations.set("vpnOnline", vpnInfo.getOnline());
        // 记录任务详细信息
        updateTask(taskDetailId, task, excuteSimCode, vpnInfo.getIp(), taskDynamicInfos);
    }

    private void signUsedDevice(Device excuteDevice, Integer fun) {
        Device device = deviceService.findOne(excuteDevice.getImei());
        if (null == device) {
            VirtualDevice virtualDevice = deviceService.findVirtualDeviceByImei(excuteDevice.getImei());
            if (!virtualDevice.getUsedFuns().contains(fun)) {
                virtualDevice.getUsedFuns().add(fun);
                deviceService.saveOrUpdateVirtualDeviceAccounts(virtualDevice);
            }
        } else {
            if (!device.getUsedFuns().contains(fun)) {
                device.getUsedFuns().add(fun);
                deviceService.saveOrUpdate(device);
            }
        }
    }

    private void updateUsedImei(String taskDetailId, String imei) {
        Update update = new Update();
        update.push("usedImeis", imei);
        taskDetailRepository.updateById(taskDetailId, update);
    }

    private void lockRobot(String excuteSimCode) {
        Update updateRobot = new Update();
        updateRobot.set("lockTime", new Date().getTime() + 1000 * 30);
        robotRepository.updateBySimCode(excuteSimCode, updateRobot);
    }

    private void updateTask(String taskDetailId, TaskDetail.Task task, String excuteSimCode, String vpnHost, List<TaskDetail.Task.TaskDynamicInfo> taskDynamicInfos) {
        Update update = new Update();
        update.set("tasks.$.sent", true);
        update.set("tasks.$.vpnHost", vpnHost);
        update.set("tasks.$.excuteSimCode", excuteSimCode);
        update.set("tasks.$.taskDynamicInfos", taskDynamicInfos);
        // 正式环境不记录
        update.push("usedIp", vpnHost);
        taskDetailRepository.updateTaskByNum(taskDetailId, task.getNum(), update);
    }

    private SocketRequest<Map<String, Object>> buildSocketRequest(String taskDetailId, TaskDetail.Task task, TaskExcuteBaseInfo.VpnInfo vpnInfo, Fun.Flow.Action action) {
        Map<String, Object> socketMap = new LinkedMap();
        socketMap.put("taskDetailId", taskDetailId);
        socketMap.put("num", task.getNum());
        socketMap.put("vpnHost", vpnInfo.getIp());
        socketMap.put("userName", vpnInfo.getUsername());
        socketMap.put("password", vpnInfo.getPassword());
        socketMap.put("imei", task.getDevice().getImei());
        socketMap.put("action", action);
        socketMap.put("device", task.getDevice());
        return (SocketRequest<Map<String, Object>>) new SocketRequest("start_fun", socketMap);
    }

    private JSONObject getVpn(Integer provinceId, Integer cityId, Integer didType, Device excuteDevice) throws InterruptedException {
        JSONObject jsonObject = null;
        int repeatTime = 0;
        do {
            repeatTime++;
            switch (didType) {
                case 0:
                    jsonObject = vpnService.switchIp(Area.ALL, null);
                    break;
                case 1:
                    if (null == provinceId) {
                        jsonObject = vpnService.switchIp(Area.ALL, null);
                    } else {
                        jsonObject = vpnService.switchIp(Area.PROVINCE, provinceId.toString());
                    }
                    break;
                case 2:
                    if (null == cityId || null == provinceId) {
                        jsonObject = vpnService.switchIp(Area.ALL, null);
                    } else {
                        jsonObject = vpnService.switchIp(Area.CITY, cityId.toString());
                    }
                    break;
            }
            if (jsonObject.getInteger("status") == 0) {
                if (repeatTime == 3) {
                    return null;
                }
                LoggerUtil.info("切换vpn接口调用失败暂停1秒：" + jsonObject.getInteger("errno"));
                SECONDS.sleep(1);
            }
        } while (jsonObject.getInteger("status") == 0);
        if (didType == 2 && null == cityId) {
            if (jsonObject.getString("city_id").equals("0")) {
                // 若city_id为0重新申请，并释放ip
                vpnService.releaseIp(jsonObject.getString("ip"));
                LoggerUtil.info("重新申请IP");
                return null;
            }
        }
        if (null == provinceId || null == cityId) {
            // 记录provinceId 和city_id
            deviceRepository.updateProvinceIdAndCityId(excuteDevice, Integer.valueOf(jsonObject.getString("province_id")), Integer.valueOf(jsonObject.getString("city_id")));
        }
        return jsonObject;
    }

}
